// 全局变量
let currentChart = null;

// 工具函数
function formatNumber(num) {
  if (num >= 1000000000) {
    return (num / 1000000000).toFixed(1) + "B";
  }
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M";
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + "K";
  }
  return num.toLocaleString();
}

function showLoading() {
  document.getElementById("loading").classList.remove("hidden");
  document.getElementById("singleResult").classList.add("hidden");
  document.getElementById("compareResult").classList.add("hidden");
  document.getElementById("chartContainer").classList.add("hidden");
}

function hideLoading() {
  document.getElementById("loading").classList.add("hidden");
}

function showError(message) {
  hideLoading();
  const errorDiv = document.createElement("div");
  errorDiv.className = "error";
  errorDiv.innerHTML = `<i class="fas fa-exclamation-triangle"></i> ${message}`;

  const resultsSection = document.querySelector(".results-section");
  resultsSection.appendChild(errorDiv);

  setTimeout(() => {
    errorDiv.remove();
  }, 5000);
}

// 单包查询功能
async function searchPackage() {
  const packageName = document.getElementById("packageInput").value.trim();
  const period = document.getElementById("periodSelect").value;

  if (!packageName) {
    showError("请输入包名");
    return;
  }

  showLoading();

  try {
    const response = await fetch(
      `/api/downloads/${encodeURIComponent(packageName)}?period=${period}`
    );
    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || "获取数据失败");
    }

    displaySingleResult(data);
  } catch (error) {
    showError(error.message);
  }
}

function displaySingleResult(data) {
  hideLoading();

  const resultDiv = document.getElementById("singleResult");
  const periodText = {
    "last-day": "最近一天",
    "last-week": "最近一周",
    "last-month": "最近一月",
    "last-year": "最近一年",
  };

  resultDiv.innerHTML = `
        <div class="package-header">
            <span class="package-name">${data.package}</span>
            <span class="package-version">v${data.version}</span>
        </div>
        
        <div class="download-count">
            <i class="fas fa-download"></i> ${formatNumber(
              data.downloads
            )} 次下载
            <div style="font-size: 0.4em; color: #666; margin-top: 5px;">${
              periodText[data.period]
            }</div>
        </div>
        
        <div class="package-info">
            <div class="info-item">
                <div class="info-label"><i class="fas fa-info-circle"></i> 描述</div>
                <div class="info-value">${data.description}</div>
            </div>
            
            <div class="info-item">
                <div class="info-label"><i class="fas fa-user"></i> 作者</div>
                <div class="info-value">${data.author}</div>
            </div>
            
            <div class="info-item">
                <div class="info-label"><i class="fas fa-certificate"></i> 许可证</div>
                <div class="info-value">${data.license}</div>
            </div>
            
            ${
              data.homepage
                ? `
            <div class="info-item">
                <div class="info-label"><i class="fas fa-home"></i> 主页</div>
                <div class="info-value"><a href="${data.homepage}" target="_blank">${data.homepage}</a></div>
            </div>
            `
                : ""
            }
            
            ${
              data.repository
                ? `
            <div class="info-item">
                <div class="info-label"><i class="fab fa-git-alt"></i> 仓库</div>
                <div class="info-value"><a href="${data.repository}" target="_blank">${data.repository}</a></div>
            </div>
            `
                : ""
            }
            
            ${
              data.keywords && data.keywords.length > 0
                ? `
            <div class="info-item">
                <div class="info-label"><i class="fas fa-tags"></i> 关键词</div>
                <div class="info-value">${data.keywords.join(", ")}</div>
            </div>
            `
                : ""
            }
        </div>
    `;

  resultDiv.classList.remove("hidden");
  document.getElementById("compareResult").classList.add("hidden");
  document.getElementById("chartContainer").classList.add("hidden");
}

// 多包比较功能
async function comparePackages() {
  const input = document.getElementById("compareInput").value.trim();
  const period = document.getElementById("comparePeriodSelect").value;

  if (!input) {
    showError("请输入要比较的包名");
    return;
  }

  const packages = input
    .split("\n")
    .map((pkg) => pkg.trim())
    .filter((pkg) => pkg.length > 0);

  if (packages.length < 2) {
    showError("请至少输入两个包名进行比较");
    return;
  }

  showLoading();

  try {
    const response = await fetch("/api/compare", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ packages, period }),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.error || "获取比较数据失败");
    }

    displayCompareResult(data, period);
    createChart(data);
  } catch (error) {
    showError(error.message);
  }
}

function displayCompareResult(data, period) {
  hideLoading();

  const resultDiv = document.getElementById("compareResult");
  const periodText = {
    "last-day": "最近一天",
    "last-week": "最近一周",
    "last-month": "最近一月",
    "last-year": "最近一年",
  };

  const itemsHtml = data
    .map((item, index) => {
      const rank = index + 1;
      const rankIcon =
        rank === 1
          ? '<i class="fas fa-crown" style="color: #f1c40f;"></i>'
          : rank === 2
          ? '<i class="fas fa-medal" style="color: #95a5a6;"></i>'
          : rank === 3
          ? '<i class="fas fa-medal" style="color: #cd7f32;"></i>'
          : `<span style="font-weight: bold; color: #666;">#${rank}</span>`;

      return `
            <div class="compare-item">
                <div class="compare-package-info">
                    <div class="compare-package-name">
                        ${rankIcon} ${item.package}
                        ${
                          item.error
                            ? `<span style="color: #e74c3c; font-size: 0.8em;">(${item.error})</span>`
                            : ""
                        }
                    </div>
                    ${
                      item.description
                        ? `<div class="compare-package-desc">${item.description}</div>`
                        : ""
                    }
                    ${
                      item.author
                        ? `<div class="compare-package-desc">作者: ${item.author}</div>`
                        : ""
                    }
                </div>
                <div class="compare-downloads">
                    ${item.error ? "0" : formatNumber(item.downloads)}
                    <div style="font-size: 0.6em; color: #666;">次下载</div>
                </div>
            </div>
        `;
    })
    .join("");

  resultDiv.innerHTML = `
        <h3 style="margin-bottom: 20px; color: #333;">
            <i class="fas fa-chart-bar"></i> 包下载量比较 (${periodText[period]})
        </h3>
        <div class="compare-grid">
            ${itemsHtml}
        </div>
    `;

  resultDiv.classList.remove("hidden");
  document.getElementById("singleResult").classList.add("hidden");
}

function createChart(data) {
  const chartContainer = document.getElementById("chartContainer");
  const ctx = document.getElementById("downloadChart").getContext("2d");

  // 销毁之前的图表
  if (currentChart) {
    currentChart.destroy();
  }

  const validData = data.filter((item) => !item.error);

  if (validData.length === 0) {
    return;
  }

  const labels = validData.map((item) => item.package);
  const downloads = validData.map((item) => item.downloads);

  // 生成颜色
  const colors = [
    "#cb3837",
    "#e85a4f",
    "#2ecc71",
    "#3498db",
    "#9b59b6",
    "#f39c12",
    "#e67e22",
    "#1abc9c",
    "#34495e",
    "#95a5a6",
  ];

  currentChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: labels,
      datasets: [
        {
          label: "下载次数",
          data: downloads,
          backgroundColor: colors.slice(0, validData.length),
          borderColor: colors.slice(0, validData.length),
          borderWidth: 2,
          borderRadius: 8,
          borderSkipped: false,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        title: {
          display: true,
          text: "包下载量对比图表",
          font: {
            size: 16,
            weight: "bold",
          },
          color: "#333",
        },
        legend: {
          display: false,
        },
      },
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            callback: function (value) {
              return formatNumber(value);
            },
          },
          grid: {
            color: "rgba(0, 0, 0, 0.1)",
          },
        },
        x: {
          grid: {
            display: false,
          },
        },
      },
      animation: {
        duration: 1000,
        easing: "easeOutQuart",
      },
    },
  });

  // 设置图表容器高度
  chartContainer.style.height = "400px";
  chartContainer.classList.remove("hidden");
}

// 键盘事件处理
document
  .getElementById("packageInput")
  .addEventListener("keypress", function (e) {
    if (e.key === "Enter") {
      searchPackage();
    }
  });

// 页面加载完成后的初始化
document.addEventListener("DOMContentLoaded", function () {
  // 添加一些示例提示
  const packageInput = document.getElementById("packageInput");
  const compareInput = document.getElementById("compareInput");

  packageInput.addEventListener("focus", function () {
    if (!this.value) {
      this.placeholder = "试试输入: react, vue, lodash, express...";
    }
  });

  packageInput.addEventListener("blur", function () {
    this.placeholder = "输入包名，如：react, vue, lodash";
  });

  compareInput.addEventListener("focus", function () {
    if (!this.value) {
      this.placeholder = "试试比较这些包：\nreact\nvue\nangular\nsvelte";
    }
  });

  compareInput.addEventListener("blur", function () {
    this.placeholder = "输入多个包名，每行一个，如：\nreact\nvue\nangular";
  });
});
